package com.tsing.mapper.impl;

import com.tsing.common.framwork.mapper.CommonDao;
import com.tsing.common.result.PageResult;
import com.tsing.mapper.AuthMapper;
import com.tsing.pojo.entity.ApUserRealname;
import com.tsing.pojo.entity.TlUser;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 吴阳基
 * @datetime 2023/12/4 18:52
 */
public class AuthMapperImpl extends CommonDao implements AuthMapper {
    @Override
    public PageResult<TlUser> list(Integer page, Integer size, Integer status){
        int offset = (page - 1) * size;
        PageResult<TlUser> result = new PageResult<>();

        String statusCondition = (status != null) ? "AND status = ?" : "";
        String sql = "SELECT * FROM tl_user WHERE 1=1 " + statusCondition + " LIMIT ? OFFSET ?";

        List<Object> params = new ArrayList<>();
        if (status != null) {
            params.add(status);
        }

        params.add(size);
        params.add(offset);

        List<TlUser> data = null;
        try {
            data = executeQuery(TlUser.class, sql, params.toArray());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        result.setData(data);

        // 如果 status 为 null，则查询所有记录，否则查询具有特定状态的记录
        String countSql = (status != null) ? "SELECT COUNT(*) FROM tl_user WHERE status = ?" : "SELECT COUNT(*) FROM tl_user";

        // 根据状态是否为 null 查询总数
        long total = 0;
        try {
            total = (status != null) ? executeCount(countSql, new Object[]{status}) : executeCount(countSql, null);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        try {
            result.setTotal(executeCount(
                    "SELECT count(?) FROM tl_user",
                    new Object[]{1}));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        result.setSize(size);
        result.setCurrentPage(page);
        result.setCode(200);

        return result;
    }

    @Override
    public int update(Integer userId, Integer status) {

        int result= 0;
        try {
            result = executeUpdate(
                  "update tl_user set status = ? where userId = ?",
                  new Object[]{status,userId });
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

}
